package base.thread_JUC2.chapter04.demo07;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Task task = new Task("^_^ Task ");
        ScheduledThreadPoolExecutor pool = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);

        System.out.printf("Main: Starting at: %s\n",new Date());

        // 创建一个周期性执行的任务:延时initialDelay（1s）开启任务，待上一任务结束再延时delay（2s）执行下一任务
        // scheduleWithFixedDelay方法规定两次任务严格间隔指定时间，而scheduleAtFixedRate方法是只要到下一间隔
        ScheduledFuture<?> scheduledFuture = pool.scheduleWithFixedDelay(task, 1, 2, TimeUnit.SECONDS);

        for (int i = 0; i < 30; i++) {
            System.out.println("距离下一任务开始执行，还剩："+scheduledFuture.getDelay(TimeUnit.MILLISECONDS)+"毫秒，执行任务总数："+pool.getTaskCount());
            TimeUnit.MILLISECONDS.sleep(500);
        }

        // 结束执行器
        pool.shutdown();

    }
}
